package com.dlry.serviceImpl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dlry.db.LeaveFlowRepository;
import com.dlry.entity.DlLeave;
import com.dlry.entity.DlLeaveflow;
import com.dlry.entity.DlLoginuser;
import com.dlry.exception.UserNotFoundException;

@Service
public class LeaveFlowServiceImpl implements LeaveFlowService {
	@Autowired
	private UserService userService;
	@Autowired
	private LeaveFlowRepository leaveFlowRepository;
	@Transactional
	public void startWorkFlow(DlLeave leave) throws UserNotFoundException {
		// 创建审批流对象
		DlLeaveflow leaveflow = new DlLeaveflow();
		// 关联审配对象
		leaveflow.setDlLeave(leave);
		// 获取审配的用户
		DlLoginuser user = leave.getUser();
		// 获取上级领导用户
		DlLoginuser leader = userService.findSuperior(user);
		leaveflow.setHUser(leader);
		leaveflow.setStep(1);
		leaveflow.setCreatedAt(getNowTime());
		leaveflow.setFinish(false);
		leaveflow.setFlowType("出差");
		leaveflow.setStatu("进行中");
		leaveFlowRepository.save(leaveflow);
	}
	@Transactional
	public void nextWorkFlow(Long fId) throws UserNotFoundException {
		DlLeaveflow oldLeaveflow = leaveFlowRepository.findOne(fId);
		DlLeaveflow newFlow = new DlLeaveflow();
		oldLeaveflow.setFinish(true);
		oldLeaveflow.setEndAt(new Timestamp(new Date().getTime()));
		oldLeaveflow.setStatu("结束");
		newFlow.setDlLeave(oldLeaveflow.getDlLeave());
		newFlow.setCreatedAt(getNowTime());
		newFlow.setFinish(false);
		newFlow.setStep(oldLeaveflow.getStep() + 1);
		newFlow.setFlowType(oldLeaveflow.getFlowType());
		newFlow.setHUser(userService.findSuperior(oldLeaveflow.getHUser()));
		newFlow.setStatu("进行中");
		leaveFlowRepository.save(oldLeaveflow);
		leaveFlowRepository.save(newFlow);
	}
	@Transactional
	public void rejectWorkFlow(Long fId) {
		DlLeaveflow leaveflow = leaveFlowRepository.findOne(fId);
		leaveflow.setStatu("被驳回");
		leaveflow.setFinish(true);
		leaveflow.setEndAt(getNowTime());
		leaveFlowRepository.save(leaveflow);
	}
	@Transactional
	public void finishWorkFlow(Long fId) {
		DlLeaveflow leaveflow = leaveFlowRepository.findOne(fId);
		leaveflow.setStatu("审批通过");
		leaveflow.setEndAt(getNowTime());
		leaveflow.setFinish(true);
		leaveFlowRepository.save(leaveflow);
	}
	@Transactional
	public void revokeWorkFlow(Long fId) {
		DlLeaveflow leaveflow = leaveFlowRepository.findOne(fId);
		leaveflow.setStatu("已撤销");
		leaveflow.setEndAt(getNowTime());
		leaveflow.setFinish(true);
		leaveFlowRepository.save(leaveflow);
	}

	public List<DlLeaveflow> findFlows(Long ltId) {
		List<DlLeaveflow> flows=leaveFlowRepository.findFlowByltId(ltId);
		return flows;
	}

	public List<DlLeaveflow> findFlowings(Long hid) {
		// TODO Auto-generated method stub
		return null;
	}

	// 获取当前时间戳
	private Timestamp getNowTime() {
		return new Timestamp(new Date().getTime());
	}

}
